package cn.hasayam.test3;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.dnkilic.waveform.WaveView;
import com.hanks.htextview.HTextView;
import com.hanks.htextview.HTextViewType;
import com.iflytek.aiui.AIUIAgent;
import com.iflytek.aiui.AIUIConstant;
import com.iflytek.aiui.AIUIEvent;
import com.iflytek.aiui.AIUIListener;
import com.iflytek.aiui.AIUIMessage;
import com.sinovoice.hcicloudsdk.api.HciCloudSys;
import com.sinovoice.hcicloudsdk.api.asr.HciCloudAsr;
import com.sinovoice.hcicloudsdk.api.mt.HciCloudMt;
import com.sinovoice.hcicloudsdk.common.AuthExpireTime;
import com.sinovoice.hcicloudsdk.common.InitParam;
import com.sinovoice.hcicloudsdk.common.Session;
import com.sinovoice.hcicloudsdk.common.asr.AsrConfig;
import com.sinovoice.hcicloudsdk.common.asr.AsrInitParam;
import com.sinovoice.hcicloudsdk.common.asr.AsrRecogResult;
import com.sinovoice.hcicloudsdk.common.mt.MtConfig;
import com.sinovoice.hcicloudsdk.common.mt.MtInitParam;
import com.sinovoice.hcicloudsdk.common.mt.MtTransResult;
import com.sinovoice.hcicloudsdk.player.TTSCommonPlayer;
import com.sinovoice.hcicloudsdk.player.TTSPlayerListener;
import com.victor.loading.rotate.RotateLoading;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;

import cn.hasayam.test3.Translate.TranslateCallback;
import cn.hasayam.test3.Translate.TranslateUtil;
import cn.hasayam.test3.action.OpenAppAction;

public class MainActivity extends AppCompatActivity implements TTSPlayerListener {

    private static final String TAG = "lalala";
    ImageView m;
    RotateLoading r;
    WaveView w;
    TextView t;
    HTextView h;
    Context context;

    String AsrKey = "asr.cloud.freetalk.uyghur";
    String AsrKey2 = "asr.cloud.freetalk";
    String Developer_KEY = "替换这段文字";
    String APP_KEY = "替换这段文字";
    String Cloud_URL = "api.hcicloud.com:8888";
    String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp.pcm";
    String language ;
    String xuan;
    String style;

    Animation anim1 = new ScaleAnimation(1,0,1,0,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
    Animation anim2 = new ScaleAnimation(0,1,0,1,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
    Animation anim3 = new ScaleAnimation(1,5,1,0,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
    Animation anim11 = new TranslateAnimation(0,0,0,100);
    Animation anim12 = new AlphaAnimation(1,0);
    Animation anim21 = new TranslateAnimation(0,0,-100,0);
    Animation anim22 = new AlphaAnimation(0,1);
    AnimationSet anim31 = new AnimationSet(true);
    AnimationSet anim32 = new AnimationSet(true);


    Record record = new Record();
    AIUIAgent a;
    //private WakeUpUtil wakeup;
    private TtsPlayUtil mTtsPlayUtil;
    int mAIUIState = AIUIConstant.STATE_IDLE;

    boolean rcd = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSetting();
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= 23) {
            initPermission();
        }



        anim1.setDuration(500);
        anim1.setFillAfter(true);
        anim2.setDuration(500);
        anim2.setFillAfter(true);
        anim3.setDuration(500);
        anim3.setFillAfter(true);

        anim11.setDuration(300);
        anim11.setFillAfter(true);
        anim12.setDuration(300);
        anim12.setFillAfter(true);
        anim21.setDuration(300);
        anim21.setFillAfter(true);
        anim22.setDuration(300);
        anim22.setFillAfter(true);

        anim31.addAnimation(anim11);
        anim31.addAnimation(anim12);
        anim32.addAnimation(anim21);
        anim32.addAnimation(anim22);

        r = findViewById(R.id.r);
        m = findViewById(R.id.m);
        w = findViewById(R.id.w);
        t = findViewById(R.id.t);
        h = findViewById(R.id.h);
        h.setAnimateType(HTextViewType.LINE);



        //录音监听器
        record.lala(new RecordCall() {
            @Override
            public void dorun(RecordFuck recordFuck) {
                SpeakEnd();
            }

            @Override
            public void doling(RecordFuck recordFuck) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        w.speechEnded();
                    }
                });
            }

            @Override
            public void donot(RecordFuck recordFuck) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        w.speechStarted();
                    }
                });
            }
        });

        setText("قەدىمىڭىزگە مەرھابا");
        m.startAnimation(anim2);

        if (xuan.equals("true")){
            Log.i("悬浮窗","初始化");
            Intent intent = new Intent(MainActivity.this,WindowService.class);
            startService(intent);

        }

       }


    //讯飞语义解析监听器
    private AIUIListener mAIUIListener = new AIUIListener() {
        @Override
        public void onEvent(AIUIEvent event) {
            switch (event.eventType) {
                case AIUIConstant.EVENT_RESULT: {
                    //结果事件
                    try {
                        JSONObject bizParamJson = new JSONObject(event.info);
                        JSONObject data = bizParamJson.getJSONArray("data").getJSONObject(0);
                        JSONObject params = data.getJSONObject("params");
                        JSONObject content = data.getJSONArray("content").getJSONObject(0);
                        if (content.has("cnt_id")) {
                            String cnt_id = content.getString("cnt_id");
                            JSONObject cntJson = new JSONObject(new String(event.data.getByteArray(cnt_id), "utf-8"));
                            String sub = params.optString("sub");
                            JSONObject result = cntJson.optJSONObject("intent");
                            if (language.equals("ug")){
                                Logic(result);
                            }
                            else if (language.equals("cn")){
                                Logic2(result);
                            }
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                        setText(e.getLocalizedMessage());
                        r.stop();
                        m.startAnimation(anim2);
                    }

                } break;

                case AIUIConstant.EVENT_ERROR: {
                    //错误事件
                    Log.i( TAG,  "on event: "+ event.eventType );
                    setText(""+event.arg1+"\n"+event.info);
                    r.stop();
                    m.startAnimation(anim2);
                } break;

                default:
                    break;
            }
        }

    };

    private void Logic(JSONObject result) throws JSONException {
        //技能
        String service = result.getString("service");

        switch (service){
            case "app":{
                JSONObject semantic = result.getJSONArray("semantic").getJSONObject(0);
                JSONObject slots = semantic.getJSONArray("slots").getJSONObject(0);
                String name = slots.getString("value");
                OpenAppAction openApp = new OpenAppAction(name, MainActivity.this);
                openApp.start();
                play("ئىچىلىۋاتىدۇ");
                r.stop();
                m.startAnimation(anim2);
            }break;

            default:{
                String str = "";
                if(result.optInt("rc") == 0){
                    JSONObject answer = result.optJSONObject("answer");
                    str = answer.optString("text");
                    Log.i("答复内容",str);
                    Mt2(str);
                }else{
                    str = "خاتالىق"+result.optInt("rc");
                    Log.e("应答码", String.valueOf(result.optInt("rc")));
                    setText(str);
                }
            }break;
        }
    }

    private void Logic2(JSONObject result) throws JSONException {
        //技能
        String service = result.getString("service");

        switch (service){
            case "app":{
                JSONObject semantic = result.getJSONArray("semantic").getJSONObject(0);
                JSONObject slots = semantic.getJSONArray("slots").getJSONObject(0);
                String name = slots.getString("value");
                OpenAppAction openApp = new OpenAppAction(name, MainActivity.this);
                openApp.start();
                play2("正在打开");
                r.stop();
                m.startAnimation(anim2);
            }break;

            default:{
                String s = "";
                if(result.optInt("rc") == 0){
                    JSONObject answer = result.optJSONObject("answer");
                    s = answer.optString("text");
                    Log.i("答复内容",s);
                    setText(s);
                    play2(s);
                    r.stop();
                    m.startAnimation(anim2);
                }else{
                    s = "错误"+result.optInt("rc");
                    Log.e("应答码", String.valueOf(result.optInt("rc")));
                    setText(s);
                }
            }break;
        }
    }
    //传文本给讯飞
    private void Lala(String s){
        //SRResult = s;
//        s = "现在几点";
        checkAIUIAgent();
        if( AIUIConstant.STATE_WORKING != 	this.mAIUIState ){
            AIUIMessage wakeupMsg = new AIUIMessage(AIUIConstant.CMD_WAKEUP, 0, 0, "", null);
            a.sendMessage(wakeupMsg);
        }
        if (!TextUtils.isEmpty(s)){
            byte[] content= s.getBytes();
            AIUIMessage writeMsg = new AIUIMessage( AIUIConstant.CMD_WRITE, 0, 0, "data_type=text", content );
            a.sendMessage(writeMsg);
        }
        else {
            MainActivity.this.runOnUiThread(new Runnable() {
                @SuppressLint("SetTextI18n")
                @Override
                public void run() {
                    t.setText("...");
                    r.stop();
                    m.startAnimation(anim2);
                }
            });
        }
    }

    //语音识别
    public void Asr() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                int errcode;
                //http://doc.aicloud.com/sdk8.1.1/guide/ERROR_CODE/error-code.html
                initLing();
                AsrInitParam asrInitParam = new AsrInitParam();
                asrInitParam.addParam(AsrInitParam.PARAM_KEY_INIT_CAP_KEYS, AsrKey);
                errcode = HciCloudAsr.hciAsrInit(asrInitParam.getStringConfig());
                Log.i("错误码1",""+errcode);
                AsrConfig config = new AsrConfig();
                config.addParam(AsrConfig.SessionConfig.PARAM_KEY_CAP_KEY, AsrKey);
                config.addParam(AsrConfig.AudioConfig.PARAM_KEY_AUDIO_FORMAT, AsrConfig.AudioConfig.VALUE_OF_PARAM_AUDIO_FORMAT_PCM_16K16BIT);
                config.addParam(AsrConfig.AudioConfig.PARAM_KEY_ENCODE, AsrConfig.AudioConfig.VALUE_OF_PARAM_ENCODE_NONE);
                String sSessionConfig = config.getStringConfig();
                Session nSessionId = new Session();
                errcode = HciCloudAsr.hciAsrSessionStart(sSessionConfig, nSessionId);
                Log.i("错误码2",""+errcode);
                byte[] b = File2byte(filepath);
                AsrRecogResult asrResult = new AsrRecogResult();
                errcode = HciCloudAsr.hciAsrRecog(nSessionId, b, null, null, asrResult);
                Log.i("错误码3",""+errcode);
                final StringBuilder str = new StringBuilder();
                str.append(asrResult.getRecogItemList().get(0).getRecogResult());
                final String s = String.valueOf(str);
                MainActivity.this.runOnUiThread(new Runnable() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void run() {
                        //t.setText(s);
                        h.animateText(s);

                    }
                });
                Log.i("结果", s);
                Mt1(s);
            }
        }).start();
    }
    public void Asr2() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                int errcode;
                initLing();
                AsrInitParam asrInitParam = new AsrInitParam();
                asrInitParam.addParam(AsrInitParam.PARAM_KEY_INIT_CAP_KEYS, AsrKey2);
                errcode = HciCloudAsr.hciAsrInit(asrInitParam.getStringConfig());
                Log.i("错误码4",""+errcode);
                AsrConfig config = new AsrConfig();
                config.addParam(AsrConfig.SessionConfig.PARAM_KEY_CAP_KEY, AsrKey2);
                config.addParam(AsrConfig.AudioConfig.PARAM_KEY_AUDIO_FORMAT, AsrConfig.AudioConfig.VALUE_OF_PARAM_AUDIO_FORMAT_PCM_16K16BIT);
                config.addParam(AsrConfig.AudioConfig.PARAM_KEY_ENCODE, AsrConfig.AudioConfig.VALUE_OF_PARAM_ENCODE_NONE);
                String sSessionConfig = config.getStringConfig();
                Session nSessionId = new Session();
                errcode = HciCloudAsr.hciAsrSessionStart(sSessionConfig, nSessionId);
                Log.i("错误码5",""+errcode);
                byte[] b = File2byte(filepath);
                AsrRecogResult asrResult = new AsrRecogResult();
                errcode = HciCloudAsr.hciAsrRecog(nSessionId, b, null, null, asrResult);
                Log.i("错误码6",""+errcode);
                final StringBuilder str = new StringBuilder();
                str.append(asrResult.getRecogItemList().get(0).getRecogResult());
                final String s = String.valueOf(str);
                MainActivity.this.runOnUiThread(new Runnable() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void run() {
                        h.animateText(s);
                    }
                });
                Log.i("结果", s);
                Lala(s);
            }
        }).start();
    }
    //翻译
    public void Mt1(final String s){
        new Thread(new Runnable() {
            @Override
            public void run() {
                new TranslateUtil().translate(context, "ug-CN", "zh-CN", s,
                        new TranslateCallback() {
                    @Override
                    public void onTranslateDone(String result) {
                        Log.i("翻译结果",result);
                        Lala(result);
                    }
                });
            }
        }).start();
    }
    public void Mt2(final String s){
        new Thread(new Runnable() {
            @Override
            public void run() {
                new TranslateUtil().translate(context, "zh-CN", "ug-CN", s,
                        new TranslateCallback() {
                            @Override
                            public void onTranslateDone(final String result) {
                                Log.i("翻译结果",result);
                                MainActivity.this.runOnUiThread(new Runnable() {
                                    @SuppressLint("SetTextI18n")
                                    @Override
                                    public void run() {
                                        setText(result);
                                        play(result);
                                        r.stop();
                                        m.startAnimation(anim2);
                                    }
                                });
                            }
                        });


            }
        }).start();
    }

    //TTS
    private void play(String s){
        mTtsPlayUtil = new TtsPlayUtil(this);
        mTtsPlayUtil.initPlayer(this,"tts.cloud.uyghur");
        mTtsPlayUtil.synth(String.valueOf(s));
    }
    private void play2(String s){
        mTtsPlayUtil = new TtsPlayUtil(this);
        mTtsPlayUtil.initPlayer(this,"tts.cloud.xiaokun");
        mTtsPlayUtil.synth(String.valueOf(s));
    }
    //TTS的三个监听器
    @Override
    public void onPlayerEventStateChange(TTSCommonPlayer.PlayerEvent playerEvent) {

    }
    @Override
    public void onPlayerEventProgressChange(TTSCommonPlayer.PlayerEvent playerEvent, int i, int i1) {

    }
    @Override
    public void onPlayerEventPlayerError(TTSCommonPlayer.PlayerEvent playerEvent, int i) {

    }

    //录音结束
    private void SpeakEnd(){
        if (rcd) {
            record.Stop();
            rcd = false;
            if (language.equals("ug")) {
                Asr();

            }else if (language.equals("cn")){
                Asr2();
            }
            setText("");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                w.speechEnded();
                            }
                        });
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            w.stop();
                            r.start();
                        }
                    });
                }
            }).start();
        }
    }

    public void speakAnswer(String s) {
        setText(s);
    }

    //初始化讯飞
    private String getAIUIParams() {
        String params = "";

        AssetManager assetManager = getResources().getAssets();
        try {
            InputStream ins = assetManager.open( "cfg/aiui_phone.cfg" );
            byte[] buffer = new byte[ins.available()];

            ins.read(buffer);
            ins.close();

            params = new String(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return params;
    }
    private boolean checkAIUIAgent(){
        if( null == a ){
            Log.i( TAG, "create aiui agent" );

            //创建AIUIAgent
            a = AIUIAgent.createAgent( this, getAIUIParams(), mAIUIListener );
        }

        if( null == a ){
            final String strErrorTip = "创建 AIUI Agent 失败！";
            Log.e("初始化",strErrorTip);
        }

        return null != a;
    }

    //初始化灵云
    private static byte[] File2byte(String filePath) {
        File file = new File(filePath);
        int musicLength = (int) (file.length() / 2);
        short[] music = new short[musicLength];
        try {
            InputStream is = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            DataInputStream dis = new DataInputStream(bis);
            int i = 0;
            while (dis.available() > 0) {
                music[i] = dis.readShort();
                i++;
            }
            byte[] bytes = new byte[music.length * 2];
            ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(music);
            return bytes;
        } catch (Throwable t) {
            Log.e("", "播放失败");
        }
        return null;
    }
    void initLing(){
        InitParam initparam =new InitParam();
        String authDirPath = this.getFilesDir().getAbsolutePath();
        initparam.addParam(InitParam.AuthParam.PARAM_KEY_AUTH_PATH, authDirPath);
        initparam.addParam(InitParam.AuthParam.PARAM_KEY_CLOUD_URL,Cloud_URL);
        initparam.addParam(InitParam.AuthParam.PARAM_KEY_APP_KEY,APP_KEY);
        initparam.addParam(InitParam.AuthParam.PARAM_KEY_DEVELOPER_KEY,Developer_KEY);
        HciCloudSys.hciInit(initparam.getStringConfig(),this);
        AuthExpireTime objExpireTime =new AuthExpireTime();
        HciCloudSys.hciGetAuthExpireTime(objExpireTime);
        HciCloudSys.hciCheckAuth();
    }

    //按钮被点击，一切的开始
    public void come(View view) {
        start();
    }

    public void start(){
        if (!rcd) {
            m.startAnimation(anim3);
            w.setVisibility(View.VISIBLE);
            record.Start();
            setText("ئاڭلاۋاتىمەن...");
            rcd = true;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DisplayMetrics dm = new DisplayMetrics();
                            getWindowManager().getDefaultDisplay().getMetrics(dm);
                            w.initialize(dm);
                            w.speechStarted();

                        }
                    });
                }
            }).start();
        }
        else {
            SpeakEnd();
        }
    }

    //申请权限
    private void initPermission() {

        String storagePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        String cameraPermission = Manifest.permission.RECORD_AUDIO;
        String windowPermission = Manifest.permission.SYSTEM_ALERT_WINDOW;

        int hasStoragePermission = ActivityCompat.checkSelfPermission(this, storagePermission);
        int hasCameraPermission = ActivityCompat.checkSelfPermission(this, cameraPermission);
        int hasWindowPermission = ActivityCompat.checkSelfPermission(this,windowPermission);

        List<String> permissions = new ArrayList<>();
        if (hasStoragePermission != PackageManager.PERMISSION_GRANTED) {
            permissions.add(storagePermission);
        }

        if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
            permissions.add(cameraPermission);
        }

        //悬浮窗权限
        if (hasWindowPermission != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if(!Settings.canDrawOverlays(this)) {
                    startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 100);
                }
            }
            permissions.add(windowPermission);
        }

        if (!permissions.isEmpty()) {
            String[] params = permissions.toArray(new String[permissions.size()]);
            ActivityCompat.requestPermissions(this, params, 100);
        }

    }

    //文字淡入淡出
    public void setText(final String s){
        t.startAnimation(anim31);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        t.setText(s);
                        t.startAnimation(anim32);
                    }
                });
            }
        }).start();
    }
    public void setAsr(final String s){
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                h.animateText(s);
            }
        });
    }
    public void stopAnim(){
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                r.stop();
                m.startAnimation(anim2);
            }
        });

    }
    public void exit(View view) {
        finish();
    }
    private void getSetting(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                language = SettingDatabase.getInstance(MainActivity.this).getSettingDao().getValue("language");
                xuan = SettingDatabase.getInstance(MainActivity.this).getSettingDao().getValue("xuan");
                style = SettingDatabase.getInstance(MainActivity.this).getSettingDao().getValue("style");
                if (language == null || xuan == null || style == null){
                    SettingBean s1 = new SettingBean("language","ug");
                    SettingBean s2 = new SettingBean("xuan","false");
                    SettingBean s3 = new SettingBean("style","1");
                    SettingDatabase.getInstance(MainActivity.this).getSettingDao().insert(s1,s2,s3);
                    language = "ug"; xuan = "false"; style = "1";
                }
            }
        }).start();
    }
    public void setting(View view) {
        Intent intent = new Intent(MainActivity.this,Setting.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }


    public void test(View view) {

//        wakeup = new WakeUpUtil(this,this) {
//            @Override
//            public void wakeUp() {
//                wakeup.wake();
//            }
//        };
//        wakeup.wake();

    }

}